package com.sumainfor.wx.tenant.util;


import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class HttpUtil {

    private static class Get {
        public static final OkHttpClient OK_HTTP_CLIENT =
                new OkHttpClient.Builder()
                        .connectTimeout(50, TimeUnit.SECONDS)
                        .writeTimeout(50, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .build();
    }

    public static final OkHttpClient getInstance() {
        return Get.OK_HTTP_CLIENT;
    }

    public static Call doGet(String url) {
        OkHttpClient okHttpClient = getInstance();
        Request request = new Request.Builder()
                .url(url)
                .build();
        return okHttpClient.newCall(request);
    }


    public static Call doPost(String url, RequestBody requestBody) {
        OkHttpClient okHttpClient = getInstance();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        return okHttpClient.newCall(request);
    }

    public static Call doPostForOCR(String url, RequestBody requestBody) {
        OkHttpClient okHttpClient = getInstance();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .header("Authorization", "APPCODE c8a411a9ba8642cf8353f289558fa505")
                .header("Content-Type", "application/json; charset=UTF-8")
                .build();
        return okHttpClient.newCall(request);
    }

    /**
     * Body 通过网络请求
     *
     * @param url
     * @return 请求成功返回结果 否则返回空字符串
     */
    public static String getBody(String url) throws IOException {
        Response response = doGet(url).execute();
        if (response.isSuccessful()) {
            String result = response.body().string();
            if (!result.isEmpty()) {
                return result;
            }
        }
        response.close();
        return "";
    }

}
